package com.zyong.design.pattern.iterator.case2;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 产品目录类，使用了迭代器模式
 * @program: zyong-design-pattern
 * @ClassName: ProductCatalog
 * @author: zyong
 * @create: 2024-06-01 08:49
 */
public class ProductCatalog implements Iterable<Product> {
    // 内部使用ArrayList来存储产品
    private List<Product> products = new ArrayList<>();

    public void addProduct(Product product) {
        products.add(product);
    }

    @Override
    public Iterator<Product> iterator() {
        return new ProductIterator(products);
    }

    /**
     * 私有内部类实现迭代器接口
     */
    private class ProductIterator implements Iterator<Product> {
        private List<Product> productList;
        private int position;

        public ProductIterator(List<Product> productList) {
            this.productList = productList;
        }

        @Override
        public boolean hasNext() {
            return position < productList.size();
        }
        @Override
        public Product next() {
            if (hasNext()) {
                return productList.get(position++);
            } else {
                return null;
            }
        }
    }
}
